<?php

namespace App\Http\Controllers\Mp;

use App\Http\Resources\Mp\BookRuleResource;
use App\Models\BookRule;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;

/**
 * Class BookRuleController
 * @package App\Http\Controllers\Mp
 * @author zjw
 */
class BookRuleController extends BaseController
{
    /**
     * @param Request $request
     * @return array
     */
    public function index(Request $request)
    {
        $user = \Auth::user();
        $today = date("Y-m-d");
        $query = BookRule::afterToday()->isNotCanceled()->with(['foods','school.rule'])->orderBy('eat_date');
        if ($request->type && $request->type === 'children') {
            $rules = $query->where('school_id', $user->school_id)->get();
        } else {
            $rules = $query->toUser()->get();
        }
        $lunches = [];
        $dinners = [];
        $breakfasts = [];
        $currents = [];
        foreach ($rules as $rule) {
            switch ($rule->eat_type) {
                case BookRule::EAT_TYPE_BREAKFAST:
                    if ($rule->eat_date == $today){
                        $currents['breakfast'] = $rule;
                    } else {
                        $breakfasts[] = $rule;
                    }
                    break;
                case BookRule::EAT_TYPE_LUNCH:
                    if ($rule->eat_date == $today){
                        $currents['lunch'] = $rule;
                    } else {
                        $lunches[] = $rule;
                    }
                    break;
                case BookRule::EAT_TYPE_DINNER:
                    if ($rule->eat_date == $today){
                        $currents['dinner'] = $rule;
                    } else {
                        $dinners[] = $rule;
                    }
                    break;
            }
        }
        return [
            'lunches'=>BookRuleResource::collection(Collection::make($lunches)),
            'dinners'=>BookRuleResource::collection(Collection::make($dinners)),
            'breakfasts'=>BookRuleResource::collection(Collection::make($breakfasts)),
            'currents' => BookRuleResource::collection(Collection::make(($currents)))
        ];
    }
}
